using System.Collections.Concurrent;
using System;
namespace HB.MsgBusItem
{
    /// <summary>
    /// 权限验证
    /// </summary>
    internal class PermissionsChecker
    {
        ConcurrentDictionary<string, PermissionsItem> DicItems = new ConcurrentDictionary<string, PermissionsItem>();
        /// <summary>
        /// 验证是否被取消或被回收
        /// </summary>
        /// <param name="topic"></param>
        /// <returns></returns>
        public bool IsEnabled(string topic)
        {
            return DicItems.ContainsKey(topic) && DicItems[topic].IsActived();
        }
        /// <summary>
        /// 获取最新分组
        /// </summary>
        /// <param name="topic"></param>
        /// <returns></returns>
        public string GetNewGroup(string topic)
        {
            if (DicItems.ContainsKey(topic))
            {
                return DicItems[topic].Group;
            }
            else { return null; }
        }
        /// <summary>
        /// 移除该id下的topic权限
        /// </summary>
        /// <param name="topic"></param>
        public void Remove(string topic)
        {
            if (DicItems.ContainsKey((string)topic))
            {
                DicItems.TryRemove(topic, out _);
            }
        }
        /// <summary>
        /// 增加或更新订阅者信息
        /// </summary>
        /// <param name="topic">topic</param>
        /// <param name="group">分组</param>
        /// <param name="reference">若为null则不指定</param>
        public void AddOrUpdate(string topic, string group, WeakReference reference)
        {
            if (DicItems.ContainsKey(topic))
            {
                DicItems[topic].Group = group;
                if (reference != null)
                {
                    DicItems[topic].Target = reference;
                }
            }
            else
            {
                DicItems[topic] = new PermissionsItem() { Group = group, Target = reference };
            }

        }

        /// <summary>
        /// 更新所有订阅者的所属组
        /// </summary>
        /// <param name="newGroup"></param>
        public void UpdateAll(string newGroup)
        {
            //只更新存在的topic
            foreach (var topic in DicItems.Keys)
            {
                DicItems[topic].Group = newGroup;
            }
        }
        /// <summary>
        /// 清理所有允许
        /// </summary>
        public void Clear()
        {
            DicItems.Clear();
        }
    }
}
